//
//  UseScrollViewReader.swift
//  learn-ios
//
//  Created by Dong on 2022/4/5.
//

import SwiftUI

func color(fraction: Double) -> Color {
    Color(red: fraction, green: 1 - fraction, blue: 0.5)
}

struct UseScrollViewReader: View {
    @Namespace var topID
    @Namespace var bottomID

    var body: some View {
        // proxy只能在action中使用，否则会无法启动应用
        ScrollViewReader { proxy in
            ScrollView {
                
                // 点击回到底部按钮
                Button("Scroll to Bottom") {
                    withAnimation {
                        proxy.scrollTo(bottomID)
                    }
                }
                // View绑定ID
                .id(topID)

                VStack(spacing: 0) {
                    ForEach(0 ..< 100) { i in
                        color(fraction: Double(i) / 100)
                            .frame(height: 30)
                    }
                }

                // 点击回到顶部按钮
                Button("Top") {
                    withAnimation {
                        proxy.scrollTo(topID)
                    }
                }
                .id(bottomID)
            }
        }
    }
}

struct UseScrollViewReader_Previews: PreviewProvider {
    static var previews: some View {
        UseScrollViewReader()
    }
}
